<template>
	<div class="question-list" style="padding: 20px;">
	  <el-card>
		<template #header>
		  <div class="card-header">
			<span>题目管理</span>
			<div>
			  <el-button type="primary" :icon="Plus" @click="goToCreate">
				新增题目
			  </el-button>
			</div>
		  </div>
		</template>
  
		<el-form :model="searchForm" inline>
		  <el-form-item label="科目">
			<el-select
			  v-model="searchForm.subject_id"
			  placeholder="请选择科目"
			  clearable
			  @change="handleSubjectChange"
			>
			  <el-option
				v-for="item in subjects"
				:key="item.id"
				:label="item.name"
				:value="item.id"
			  />
			</el-select>
		  </el-form-item>
  
		  <el-form-item label="章节">
			<el-select
			  v-model="searchForm.chapter_id"
			  placeholder="请选择章节"
			  clearable
			>
			<el-option
				v-for="item in chapters"
				:key="item.id"
				:label="item.name"
				:value="item.id"
			  />
			</el-select>
		  </el-form-item>
  
		  <el-form-item label="题型">
			<el-select
			  v-model="searchForm.question_type"
			  placeholder="请选择题型"
			  clearable
			>
			  <el-option label="单选题" :value="1" />
			  <el-option label="多选题" :value="2" />
			  <el-option label="判断题" :value="3" />
			  <el-option label="填空题" :value="4" />
			  <el-option label="简答题" :value="5" />
			</el-select>
		  </el-form-item>
  
		  <el-form-item label="关键词">
			<el-input
			  v-model="searchForm.keyword"
			  placeholder="请输入题目内容关键词"
			  clearable
			/>
		  </el-form-item>
  
		  <el-form-item>
			<el-button type="primary" @click="loadData">搜索</el-button>
			<el-button @click="resetSearch">重置</el-button>
		  </el-form-item>
		</el-form>
  
		<el-table
			
		  :data="tableData"
		  border
		  stripe
		  v-loading="loading"
		  style="width: 100%"
		>
		  <el-table-column prop="id" label="ID" width="80" align="center"  />
		  <el-table-column prop="subject" label="科目" width="120" align="center" >
			<template #default="{row}">{{ row.subject.name }}</template>
		  </el-table-column>
		  <el-table-column prop="chapter" label="章节" width="120" align="center" >
			<template #default="{row}">{{row.chapter? row.chapter.name : '未知章节' }}</template>
		  </el-table-column>
		  <el-table-column label="题型" width="100" align="center">
			<template #default="{ row }">
			  {{ getTypeName(row.question_type) }}
			</template>
		  </el-table-column>
		  <el-table-column label="正确答案"  width="100" prop="answer"  align="center"></el-table-column>
		  <el-table-column label="题目内容"  width="200" align="center">
			<template #default="{ row }">
			  <div class="content-cell" v-html="row.content" />
			</template>
		  </el-table-column>
		  <el-table-column label="题目选项" width="300" align="left">
			<template #default="{ row }">
				<div style="display: flex; align-items: left;">
					<div v-if="row.options && row.options.length">
					<div v-for="opt in row.options" :key="opt.id" class="option-item">
						<el-tag 
						:type="opt.is_correct ? 'success' : ''"
						size="small"
						>
						{{ opt.option_key }}. 
						</el-tag>
						<span v-html="opt.option_content" class="option-content"></span>
					</div>
					</div>
					<span v-else>无选项</span>
				</div>
			</template>
			</el-table-column>
			<el-table-column label="答案解析" width="300" align="center" prop="analysis" ></el-table-column>
		  <el-table-column label="难度" width="180" align="center">
			<template #default="{ row }">
			  <el-rate v-model="row.difficulty" disabled :max="5" />
			</template>
		  </el-table-column>
		  <el-table-column label="状态" width="100" align="center">
			<template #default="{ row }">
			  <el-tag :type="row.status === 1 ? 'success' : 'danger'">
				{{ row.status === 1 ? '启用' : '禁用' }}
			  </el-tag>
			</template>
		  </el-table-column>
		  <el-table-column label="题目分值" width="90" align="center" prop="score" ></el-table-column>

		  <el-table-column prop="created_at" align="center" label="创建时间" width="180" />
		  <el-table-column label="操作" width="180" fixed="right">
			<template #default="{ row }">
			  <el-button
				type="primary"
				size="small"
				:icon="Edit"
				@click="goToEdit(row.id)"
			  />
			  <el-button
				type="danger"
				size="small"
				:icon="Delete"
				@click="handleDelete(row.id)"
			  />
			</template>
		  </el-table-column>
		</el-table>
  
		<div class="pagination">
		  <el-pagination
			v-model:current-page="pagination.current"
			v-model:page-size="pagination.size"
			:total="pagination.total"
			:page-sizes="[10, 20, 50, 100]"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="loadData"
			@current-change="loadData"
		  />
		</div>
	  </el-card>

	  
	</div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted } from 'vue';
  import { useRouter } from 'vue-router';
  import { Edit, Delete, Plus } from '@element-plus/icons-vue';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { getQuestionList, deleteQuestion, getSubjects, getChapterTree,all } from '/@/api/question/index';
  import type { QuestionListItem, Subject, Chapter } from '/@/types/question';
  
  const router = useRouter();
  
  const subjects = ref<Subject[]>([]);
  const chapters = ref<Chapter[]>([]);
  const tableData = ref<QuestionListItem[]>([]);
  const loading = ref(false);
  
  const searchForm = ref({
	subject_id: undefined,
	chapter_id: undefined,
	question_type: undefined,
	keyword: ''
  });
  
  const pagination = ref({
	current: 1,
	size: 10,
	total: 0
  });
  
  // 加载数据
  const loadData = async () => {
	try {
	  loading.value = true;
	  const params = {
		...searchForm.value,
		page: pagination.value.current,
		size: pagination.value.size
	  };
	  const res = await getQuestionList(params);
	  tableData.value = res.data.list;
	  pagination.value.total = res.data.total;
	} catch (error) {
	  console.error('加载题目列表失败:', error);
	  ElMessage.error('加载题目列表失败');
	} finally {
	  loading.value = false;
	}
  };
  
  // 初始化数据
  const initData = async () => {
	try {
	  const [subjectsRes, chaptersRes] = await Promise.all([
	   getSubjects(),
		getChapterTree({subject_id:0})
	  ]);
	  
	  subjects.value = subjectsRes.data;
	  chapters.value = chaptersRes.data;
	} catch (error) {
	  console.error('初始化数据失败:', error);
	}
  };
  
  const getSubjectsList = () => {
	getSubjects().then((res:any) => {
		console.log('sadda',res)

	})
  }
  // 科目改变时重置章节
  const handleSubjectChange = async (e:any) => {
	console.log('dasda',e)
	const res = await all({id:e})
	chapters.value = res.data
	searchForm.value.chapter_id = undefined;

  };
  
  // 重置搜索
  const resetSearch = () => {
	searchForm.value = {
	  subject_id: undefined,
	  chapter_id: undefined,
	  question_type: undefined,
	  keyword: ''
	};
	pagination.value.current = 1;
	loadData();
  };
  
  // 获取题型名称
  const getTypeName = (type: number) => {
	const types = {
	  1: '单选题',
	  2: '多选题',
	  3: '判断题',
	  4: '填空题',
	  5: '简答题'
	};
	return types[type] || '未知';
  };
  
  // 跳转到新增页面
  const goToCreate = () => {
	router.push('/question/create');
  };
  
  // 跳转到编辑页面
  const goToEdit = (id: number) => {
	router.push(`/question/edit/${id}`);
  };
  
  // 删除题目
  const handleDelete = (id: number) => {
	ElMessageBox.confirm('确定要删除这道题目吗?', '提示', {
	  type: 'warning'
	})
	  .then(async () => {
		try {
		  await deleteQuestion(id);
		  ElMessage.success('删除成功');
		  loadData();
		} catch (error) {
		  console.error('删除题目失败:', error);
		  ElMessage.error('删除题目失败');
		}
	  })
	  .catch(() => {});
  };
  
  onMounted(() => {
	getSubjectsList();
	initData();
	loadData();
  });
  </script>
  
  <style scoped>
  .card-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
  }
  
  .content-cell {
	max-height: 100px;
	overflow: hidden;
	text-overflow: ellipsis;
	display: -webkit-box;
	-webkit-line-clamp: 3;
	-webkit-box-orient: vertical;
  }
  
  .pagination {
	margin-top: 20px;
	display: flex;
	justify-content: flex-end;
  }
  </style>